import * as R from 'ramda';

import { CSS_CLASS_PREFIX } from '../lib/constants';
import { createBem } from '@r-magician/utils';
import dayjs from 'dayjs';

export const cssClass = createBem(CSS_CLASS_PREFIX);

export const optionsToValueEnum = (options = []) => {
  return options.reduce((acc, item) => {
    return {
      ...acc,
      [item.value]: item.label,
    };
  }, {});
};

export const formatterTime = (v) => {
  return dayjs(v).format('YYYY-MM-DD HH:mm:ss');
};

export const unResWrapper =
  (requestFn) =>
  (...args) => {
    return requestFn(...args).then((res) => res.data);
  };

export const paginationWrapper = (requestFn) => (params) => {
  const { current, pageSize, ...data } = params;
  return requestFn({
    page: current,
    size: pageSize,
    ...data,
  }).then((res) => {
    return {
      data: res.data.docs,
      total: res.data.total,
    };
  });
};
export const covertTreeData = (list, fn) => {
  const newList = R.clone(list);
  return newList.map((item) => {
    if (fn && typeof fn === 'function') {
      item = fn(item);
    } else {
      item.value = item.id;
      item.key = item.id;
      item.title = item.name;
    }

    if (item.children && item.children.length) {
      item.children = covertTreeData(item.children, fn);
    }
    return item;
  });
};

export const flattenTree = (treeData) => {
  const res = [];
  for (let i = 0; i < treeData.length; i++) {
    const node = treeData[i];
    if (node) {
      res.push(node);
      if (node.children && node.children.length > 0) {
        res.push(...flattenTree(node.children));
      }
    }
  }
  return res;
};

export const calcProTableScrollHeight = (wrapperHeight) => {
  const defaultHeights = {
    searchBarHeight: 80,
    searchBarTableSpace: 16,
    tableToolbarHeight: 64,
    tableHeadHeight: 61,
  };

  const proTableExcludeBodyHeight = Object.keys(defaultHeights).reduce(
    (acc, item) => {
      return acc + defaultHeights[item];
    },
    0,
  );
  return `calc(100vh - ${wrapperHeight}px - ${proTableExcludeBodyHeight}`;
};

export const appendEllipsis = (columns = []) => {
  return columns.map((item, index) => {
    if (item.render || item.title === '操作' || index === 0) return item;
    item.ellipsis = true;
    return item;
  });
};
